<template>
    <el-dialog v-model="dialogFormVisible" title='删除操作' width="30%" center>
        <span v-if="adminId" style="font-size: 13px;">是否去掉此用户的管理员职位？删除后此用户将重新展现在用户列表中</span>
        <span v-else>请慎重操作，删除后此用户将永久失去登录资格</span>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="deleteAdmin">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, ref } from 'vue'
import {
    bus
} from "@/utils/mitt.js"
import {
    changeIdentity, deleteUser
} from '@/api/userinfo.js'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/store/userinfo.js'
import { tracking } from '@/utils/operation.js'

//用户信息
const userStore = useUserInfoStore()
const adminId = ref()
const userid = ref()
const account = ref()
const name = ref()

bus.on('deleteId', (id: number) => {
    adminId.value = id
})
bus.on('deleteUserId', (userInfo: any) => {
    userid.value = userInfo.id
    account.value = userInfo.account
    name.value = userInfo.name
})
// 删除管理员
const emit = defineEmits(['success'])
const deleteAdmin = async () => {
    if (adminId.value) {
        const res = await changeIdentity(adminId.value, '用户')
        if (res.data.status === 0) {
            ElMessage.success(res.data.message)
            bus.emit('offDialog', 2)
            dialogFormVisible.value = false
            //重新加载用户本地数据
            userStore.fetchUserInfo(userStore.id)
        } else {
            ElMessage.error('对管理员降职失败')
            dialogFormVisible.value = false
        }
    }
    if (userid.value) {
        const res = await deleteUser(userid.value, account.value)
        if (res.data.status === 0) {
            ElMessage({
                message: '删除用户成功',
                type: 'success',
            })
            bus.emit('offDialog', 1)
            dialogFormVisible.value = false
            //重新加载用户本地数据
            userStore.fetchUserInfo(userStore.id)
            tracking('超级管理员',userStore.name,name.value,'高级','删除')
        } else {
            ElMessage.error('删除用户失败')
            dialogFormVisible.value = false
        }
    }

}

// 弹窗开关
const dialogFormVisible = ref(false)

// 打开编辑管理员的弹窗
const open = () => {
    dialogFormVisible.value = true
}

defineExpose({
    open
})

onBeforeUnmount(() => {
    bus.all.clear()
})
</script>

<style lang="scss" scoped></style>